import OSSImageUpload from '@/components/OSSImageUpload'
import { UPDATE_USER } from '@/graphql/user'
import { useSelector } from 'react-redux'
import {
  PageContainer, ProForm, ProFormInstance, ProFormText, ProFormTextArea,
} from '@ant-design/pro-components'
import { useMutation } from '@apollo/client'
import {
  Col, Row, message, Form
} from 'antd'
import { useEffect, useRef } from 'react'
import { IState } from '@/utils/types'

type IState = typeof IState

/**
* 个人信息页面
*/
const My = () => {
  const formRef = useRef<ProFormInstance>()
  const userInfo = useSelector((state: IState) => state.userInfo)

  const [updateUserInfo] = useMutation(UPDATE_USER)

  useEffect(() => {
    if (!userInfo.tel) return;
    formRef.current?.setFieldsValue({
      tel: userInfo.tel,
      name: userInfo.name,
      desc: userInfo.desc,
      avatar: {
        url: userInfo.avatar,
      },
    })
  }, [userInfo])
  return (
    <PageContainer>
      <ProForm
        formRef={formRef}
        layout="horizontal"
        submitter={{
          resetButtonProps: {
            style: {
              display: 'none',
            },
          },
        }}
        onFinish={async (values: { name: string; desc: string; avatar: { url: string; } }) => {
          const res = await updateUserInfo({
            variables: {
              id: userInfo.id,
              params: {
                name: values.name,
                desc: values.desc,
                avatar: values.avatar[0]?.url || '',
              },
            },
          })
          if (res.data.updateUserInfo.code === 200) {
            await userInfo.refetchHandler()
            message.success(res.data.updateUserInfo.message)
            return
          }
          message.error(res.data.updateUserInfo.message)
        }}
      >
        <Row gutter={20}>
          <Col>
            <ProFormText
              name="tel"
              label="手机号"
              tooltip="不能修改"
              disabled
            />
            <ProFormText
              name="name"
              label="昵称"
              placeholder="请输入昵称"
            />
            <ProFormTextArea
              name="desc"
              label="简介"
              placeholder="请输入简介信息"
            />
          </Col>
          <Col>
            <Form.Item 
            name="avatar"
            // 以下两条是必须的
	          valuePropName="fileList" 
	          // 如果没有下面这一句会报错
	          getValueFromEvent={e => {
              if (Array.isArray(e)) {
                  return e
              }
              return e && e.fileList
            }}
            >
              <OSSImageUpload label="更改头像" />
            </Form.Item>
          </Col>
        </Row>
      </ProForm>
    </PageContainer>
  )
}

export default My
